<template>
  <div class="page-container main-view">
    <el-row :gutter="0" class="page-query-box">
      <DifinCollapse
        :show="dataContainer.showSearch"
        :showBt="true"
        @onClick="dataContainer.showSearch = !dataContainer.showSearch"
      >
        <el-col :span="24" :xs="24">
          <el-form
            :model="dataContainer.form"
            ref="QueryFormRef"
            :inline="true"
            label-width="110px"
          >
            <el-row :gutter="0">
              <el-col class="anchor-point-target" :span="6" :xs="6">
                <el-form-item label="车辆品牌" prop="brand">
                  <el-input
                    v-model="dataContainer.form.brand"
                    placeholder="请输入品牌"
                    clearable
                    @clear="handleQuery"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="6">
                <el-form-item label="车辆型号" prop="model">
                  <el-input
                    v-model="dataContainer.form.model"
                    placeholder="请输入型号"
                    clearable
                    @clear="handleQuery"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="6">
                <el-form-item label="车辆ID" prop="id">
                  <el-input
                    v-model="dataContainer.form.id"
                    placeholder="请输入车辆ID"
                    clearable
                    @clear="handleQuery"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="6">
                <el-form-item label="日租金范围" prop="dailyRateRange">
                  <el-input-number
                    v-model="dataContainer.form.minDailyRate"
                    :min="0"
                    placeholder="最低"
                    style="width: 45%"
                    @change="handleQuery"
                  />
                  <span style="margin: 0 5px">-</span>
                  <el-input-number
                    v-model="dataContainer.form.maxDailyRate"
                    :min="0"
                    placeholder="最高"
                    style="width: 45%"
                    @change="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="6">
                <el-form-item label="车辆状态" prop="status">
                  <el-select
                    style="width: 100%"
                    v-model="dataContainer.form.status"
                    placeholder="请选择状态"
                    clearable
                    @clear="handleQuery"
                    @change="handleQuery"
                  >
                    <el-option label="可租" value="可租" />
                    <el-option label="已租" value="已租" />
                    <el-option label="维修中" value="维修中" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="12">
                <el-form-item label=" ">
                  <el-button type="primary" @click="handleQuery">
                    <SvgIcon
                      :style="'width:15px;height:15px;margin-right:5px;'"
                      name="svg:search-bt.svg"
                    ></SvgIcon>
                    查询
                  </el-button>
                  <el-button @click="resetQuery">
                    <SvgIcon
                      :style="'width:15px;height:15px;margin-right:5px;'"
                      name="svg:redo.svg"
                    ></SvgIcon>
                    重置
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </DifinCollapse>
    </el-row>
    <div class="table-box content-container page-content-box">
      <div class="top-container">
        <div class="left">
          <el-button
            v-if="hasPermi(['sys:car:add'])"
            type="primary"
            @click="handleAdd"
          >
            新增车辆
          </el-button>
          <el-button plain type="primary" @click="handleExport">
            导出车辆数据
          </el-button>
          <el-button
            plain
            type="danger"
            v-if="dataContainer.currentRows.length > 0"
            @click="handleDelete(dataContainer.currentRows)"
          >
            批量删除：{{ dataContainer.currentRows.length }}
          </el-button>
          <p style="margin: 0; padding: 0">
            车辆管理系统，支持车辆信息的增删改查。
          </p>
        </div>
        <div class="right">
          <el-button circle @click="resetQuery">
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:redo.svg"
            ></SvgIcon>
          </el-button>
          <el-button
            circle
            @click="dataContainer.showSearch = !dataContainer.showSearch"
          >
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:search-bt.svg"
            ></SvgIcon>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="dataContainer.loading"
          :data="dataContainer.list"
          border
          @cell-dblclick="handleCopyVale"
          @sort-change="handleSortChange"
          height="100%"
        >
          <el-table-column
            label="多选组件"
            align="center"
            width="40"
            fixed="left"
            class-name="small-padding fixed-width"
          >
            <template #header>
              <el-checkbox
                style="height: fit-content"
                v-model="dataContainer.checked__"
                @change="
                  (e) => {
                    changeAllCheck(e);
                    handleSelectionChange(
                      dataContainer.list.filter((e) => e.checked__)
                    );
                  }
                "
                label=""
                size="large"
              />
            </template>
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.checked__"
                :disabled="isDisabled(scope.row)"
                @change="
                  () => {
                    handleSelectionChange(
                      dataContainer.list.filter((e) => e.checked__)
                    );
                  }
                "
                label=""
                size="large"
              />
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
            fixed="left"
          />
          <el-table-column
            label="车辆ID"
            show-overflow-tooltip
            align="center"
            min-width="170"
            prop="_id"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          />
          <el-table-column
            label="车辆品牌"
            show-overflow-tooltip
            align="center"
            prop="brand"
            min-width="120"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          />
          <el-table-column
            label="车辆型号"
            show-overflow-tooltip
            align="center"
            prop="model"
            min-width="120"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          />
          <el-table-column
            label="日租金(元)"
            show-overflow-tooltip
            align="center"
            prop="dailyRate"
            min-width="100"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          >
            <template #default="scope">
              {{ scope.row.dailyRate }} 元/天
            </template>
          </el-table-column>
          <el-table-column
            label="车辆状态"
            show-overflow-tooltip
            align="center"
            prop="status"
            min-width="100"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          >
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status || "可租" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="200"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button link type="default" @click="handleDetails(scope.row)">
                查看
              </el-button>
              <el-button link type="danger" @click="handleDelete([scope.row])">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          v-show="true"
          :total="dataContainer.config.total"
          :background="true"
          :current-page="dataContainer.params.pageNum"
          :page-size="dataContainer.params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :pager-count="7"
          @size-change="
            (size) => {
              dataContainer.params.pageSize = size;
              getDataList();
            }
          "
          @current-change="
            (page) => {
              dataContainer.params.pageNum = page;
              getDataList();
            }
          "
        />
      </div>
    </div>
    <CarDetailDialog
      ref="carDetailDialogRef"
      @error="(msg) => messageError(msg)"
    />
  </div>
</template>

<script>
/**
 * 页面例子
 */
import {
  defineComponent,
  onBeforeUnmount,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onMounted,
} from "vue";
import { useRouter } from "vue-router";
import { copyValue } from "@/common/OtherTools";
import DictTags from "@/components/DictTags.vue";
import { debounceFn } from "@/common/DebounceAndThrottle";
import { responseData } from "./common/Data.js";
import { messageSuccess, confirm } from "@/action/MessagePrompt.js";
import SvgIcon from "@/components/svgIcon/index.vue";
import { hasPermi } from "@/action/PowerTools";
import DifinCollapse from "@/components/DifinCollapse.vue";
import { saveAs } from "file-saver";
import carsApi from "@/http/cars.js";
import { ElMessageBox } from "element-plus";
import CarDetailDialog from "@/components/CarDetailDialog.vue";

export default defineComponent({
  components: {
    DictTags,
    SvgIcon,
    DifinCollapse,
    CarDetailDialog,
  },
  setup() {
    const router = useRouter();
    const dataContainer = reactive({
      loading: false,
      showSearch: true,
      checked__: false, //是否全选
      form: {
        brand: "",
        model: "",
        id: "",
        minDailyRate: null,
        maxDailyRate: null,
        status: "",
      },
      params: {
        //基础参数
        pageNum: 1,
        pageSize: 10,
      },
      config: {
        total: 0,
      },
      list: [], //当前展示的数据列表
      currentRows: [], //当前多选的数据列表
      optionList: [
        { value: true, label: "不可选择", elTagType: "danger" },
        { value: false, label: "可选择", elTagType: "primary" },
      ],
    });
    /** 获取数据列表 */
    const getDataList = debounceFn(function () {
      if (dataContainer.loading) return;
      dataContainer.loading = true;

      // 构建查询参数
      const params = {
        page: dataContainer.params.pageNum,
        limit: dataContainer.params.pageSize,
        brand: dataContainer.form.brand,
        model: dataContainer.form.model,
        status: dataContainer.form.status,
        minPrice: dataContainer.form.minDailyRate,
        maxPrice: dataContainer.form.maxDailyRate,
      };

      // 清理无效参数
      for (const key in params) {
        if (
          params[key] === "" ||
          params[key] === null ||
          params[key] === undefined
        ) {
          delete params[key];
        }
      }

      carsApi
        .getCarList(params)
        .then((res) => {
          if (
            res.success &&
            res.data &&
            res.data.cars &&
            Array.isArray(res.data.cars)
          ) {
            dataContainer.list = res.data.cars.map((car) => ({
              ...car,
              id: car._id || car.id,
              dailyRate: car.dailyRate || 0,
              checked__: false,
            }));
            dataContainer.config.total =
              res.data.pagination?.total || res.data.cars.length;
          } else {
            dataContainer.list = [];
            dataContainer.config.total = 0;
            if (!res.success) {
              messageError(res.message || "获取车辆列表失败");
            }
          }
          /** 默认不选择 */
          dataContainer.checked__ = false;
          /** 清空当前多选的数据 */
          handleSelectionChange([]);
        })
        .catch((err) => {
          console.error("获取车辆列表失败", err);
          messageError(err.message || "获取车辆列表失败");
          dataContainer.list = [];
          dataContainer.config.total = 0;
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }, 300);
    getDataList();
    /** 双击单元格，复制单元格内容 */
    function handleCopyVale(_, __, ___, event) {
      copyValue(event.target.innerText);
      messageSuccess("复制成功，内容为：" + event.target.innerText);
    }
    /** 排序触发事件 */
    function handleSortChange(column, prop, order) {
      dataContainer.form.orderByColumn = column.prop;
      dataContainer.form.isAsc = column.order;
      getDataList();
    }
    /** 搜索按钮操作 */
    function handleQuery() {
      dataContainer.params.pageNum = 1;
      getDataList();
    }
    /** 重置按钮操作 */
    function resetQuery() {
      dataContainer.form = {
        brand: "",
        model: "",
        id: "",
        minDailyRate: null,
        maxDailyRate: null,
        status: "",
      };
      handleQuery();
    }
    /** 导出数据 */
    function handleExport() {
      // 实现车辆数据导出功能
      const jsonStr = JSON.stringify(dataContainer.list, null, 2);
      const blob = new Blob([jsonStr], {
        type: "application/json;charset=utf-8",
      });
      saveAs(blob, "车辆数据.json");
      messageSuccess("车辆数据导出成功！");
    }
    /** 新增按钮操作 */
    function handleAdd() {
      router.push({
        name: "car-add",
      });
    }
    /** 详情按钮操作 */
    function handleDetails(row) {
      const carId = row._id || row.id;
      if (!carId) {
        messageError("无法获取车辆ID");
        return;
      }

      // 使用车辆详情组件
      if (carDetailDialogRef.value) {
        carDetailDialogRef.value.openDialog(carId);
      }
    }
    /** 编辑按钮操作 */
    function handleEdit(row, querys) {
      const carId = row._id || row.id;
      if (!carId) {
        messageError("无法获取车辆ID");
        return;
      }

      router.push({
        name: "car-edit",
        params: {
          id: carId,
        },
        query: querys,
      });
    }
    /** 删除 */
    function handleDelete(rows) {
      const ids = rows.map((item) => item._id || item.id).filter((id) => id);

      if (ids.length === 0) {
        messageError("无法获取车辆ID");
        return;
      }

      confirm("确认删除所选车辆？", "提示")
        .then(() => {
          dataContainer.loading = true;

          // 如果是批量删除，使用Promise.all处理多个请求
          if (ids.length > 1) {
            const deletePromises = ids.map((id) => carsApi.deleteCar(id));

            Promise.all(deletePromises)
              .then(() => {
                messageSuccess(`已成功删除 ${ids.length} 辆车`);
                getDataList();
              })
              .catch((err) => {
                console.error("批量删除车辆失败", err);
                messageError(err.message || "批量删除车辆失败");
              })
              .finally(() => {
                dataContainer.loading = false;
              });
          } else {
            // 单个删除
            carsApi
              .deleteCar(ids[0])
              .then(() => {
                messageSuccess("车辆删除成功");
                getDataList();
              })
              .catch((err) => {
                console.error("删除车辆失败", err);
                messageError(err.message || "删除车辆失败");
              })
              .finally(() => {
                dataContainer.loading = false;
              });
          }
        })
        .catch(() => {});
    }
    /** 批次确认多选操作 */
    function changeAllCheck(value) {
      if (!value) {
        dataContainer.list.forEach((item) => {
          item.checked__ = false;
        });
      } else {
        dataContainer.list.forEach((item) => {
          if (isDisabled(item)) {
            item.checked__ = false;
            return;
          }
          item.checked__ = true;
        });
      }
    }
    /** 计算批量操作按钮的显示隐藏 */
    function isDisabled(row) {
      /** 如果该条数据是不可选择的话可以设置 */
      return row.disabled;
    }
    // 多选框选中数据
    function handleSelectionChange(selection) {
      dataContainer.currentRows = selection || [];
    }
    /** 获取车辆状态对应的标签类型 */
    function getStatusType(status) {
      switch (status) {
        case "可租":
          return "success";
        case "已租":
          return "warning";
        case "维修中":
          return "danger";
        default:
          return "info";
      }
    }
    onMounted(() => {
      getDataList();
    });

    const carDetailDialogRef = ref(null);

    return {
      dataContainer,
      getDataList,
      handleCopyVale,
      handleSortChange,
      handleQuery,
      resetQuery,
      handleExport,
      handleAdd,
      handleDetails,
      handleEdit,
      handleDelete,
      hasPermi,
      changeAllCheck,
      isDisabled,
      handleSelectionChange,
      getStatusType,
      carDetailDialogRef,
    };
  },
});
</script>

<style lang="scss" scoped>
.main-view {
  display: flex;
  flex-direction: column;
  /** 页面间隔css变量，可自行调节 */
  --view-gap: 10px;
  > .page-query-box {
    margin: 0 0 var(--view-gap) 0 !important;
    padding: var(--view-gap) var(--view-gap) 0px var(--view-gap);
    :deep(.el-form-item) {
      margin-bottom: var(--view-gap) !important;
    }
    :deep(.el-form-item--default) {
      width: 100%;
      margin-right: 0;
    }
  }
  > .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: var(--view-gap) var(--view-gap);
    box-sizing: border-box;
    background: #fff;
    > .top-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0px 0 var(--view-gap) 0;
      > .left {
        display: flex;
        flex-direction: row;
        align-items: center;
        > * {
          margin: 0 var(--view-gap) 0 0 !important;
        }
      }
      > .right {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        > * {
          margin: 0 0px 0 var(--view-gap) !important;
        }
      }
    }
    > .table-container {
      flex: 1 1 auto;
      height: 0;
      overflow: auto;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    margin: var(--view-gap) 0 0 0;
  }
}
</style>
